<template>
  <div class="container">
    <h1>Update Data</h1>
    <div class="form-group1">
      <label for="updateId">Update ID:</label>
      <input type="number" id="updateId" v-model="id" />
    </div>
    <div class="form-group2">
      <label for="updateItemName">New Item Name:</label>
      <input type="text" id="updateItemName" v-model="item_name" />
    </div>
    <div class="form-group3">
      <label for="updateValue">New Value:</label>
      <input type="text" id="updateValue" v-model="value" />
    </div>
    <button @click="updateData">Update Data</button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const id = ref<number | null>(null)
const item_name = ref('')
const value = ref('')

const route = useRoute()

onMounted(() => {
  if (route.params.id) {
    id.value = Number(route.params.id)
    // Fetch current data and populate item_name and value fields
    fetch(`/api/data/${id.value}`)
      .then((response) => response.json())
      .then((data) => {
        item_name.value = data.item_name
        value.value = data.value
      })
      .catch((error) => {
        console.error('Error:', error)
      })
  }
})

function updateData() {
  if (id.value !== null) {
    fetch(`/api/update/${id.value}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ item_name: item_name.value, value: value.value })
    })
      .then((response) => response.json())
      .then((data) => {
        alert(data.message)
      })
      .catch((error) => {
        console.error('Error:', error)
      })
  }
}
</script>

<style scoped>
/* Add your styles here */
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  max-width: 600px;
  width: 100%;
  padding: 20px;
  background: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  margin: 50px auto;
  .form-group1 label {
    font-size: 18px;
    margin-left: -55px;
  }
  .form-group2 label {
    font-size: 18px;
    margin-left: -110px;
  }
  .form-group3 label {
    font-size: 18px;
    margin-left: -60px;
  }
}

button {
  padding: 10px 15px;
  margin-top: 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}
</style>
